package com.atguigu.function;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class UserDefinedFunction_Aggreate {
    public static void main(String[] args) {

        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
        env.setParallelism(2);

        DataStreamSource<WaterSensor> waterSensorStream =
                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60));
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);

        //自定义平均值函数
        Table table = tEnv.fromDataStream(waterSensorStream);
        tEnv.createTemporaryView("sensor",table);
        //使用API文档
        table
                .groupBy($("id"))
                .select($("id"),call(MyAvg.class,$("vc")))
                .execute()
                .print();


        //使用sql自定义函数
        //1、注册函数
        tEnv.createTemporaryFunction("myAvg",MyAvg.class);
        tEnv.sqlQuery("select " +
                " id, " +
                " myAvg(vc) avg_vc" +
                " from sensor " +
                " group by id")
                .execute().print();


    }

    //自定义函数
    public static class MyAvg extends AggregateFunction<Double,Avg>{


        //返回值
        @Override
        public Double getValue(Avg acc) {
            return acc.getAvg();
        }

        //初始化累加器
        @Override
        public Avg createAccumulator() {
            return new Avg();
        }

        //定义一个约定成俗得方法
        //注意：只要是自定义的累加函数，都要实现该方法
        //该方法用来处理每一个传进来的值
        public void accumulate(Avg acc,Integer vc){
            acc.sum +=vc;
            acc.count++;
        }
    }

    public static class Avg{
        public Long sum =0L;
        public Long count = 0L;

        public Double getAvg() {
            return sum * 1.0 / count;
        }
    }
}
